﻿package com.wits.qso.service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.wits.platform.service.BaseService;
import com.wits.qso.dao.BtableDao;
import com.wits.qso.entity.Btable;
import com.wits.qso.entity.Cls;
import com.wits.qso.entity.Course;
import com.wits.qso.entity.CreContent;
import com.wits.qso.entity.Croom;
import com.wits.qso.entity.Dept;
import com.wits.qso.entity.Grade;
import com.wits.qso.entity.MaterialD;
import com.wits.qso.entity.Student;
import com.wits.qso.entity.Teacher;

@Component
public class BtableDaoService extends BaseService<Btable, String> {
	private BtableDao btableDao;
	
	@Autowired
	private CreContentService creContentService = null;
	
	@Autowired
	public void setBtableDao(BtableDao btableDao) {
		this.baseDao=btableDao;
		this.btableDao = btableDao;
	}
	
	public Btable findByIdAndTeacher(String id, Teacher teacher) {
		return btableDao.findByIdAndTeacher( id, teacher );
	}
	
	/**
	 * 根据教室ID获取课节
	 * @param crmId 教室Id
	 * @return
	 */
	public List<Btable> findByCroom(String crmId) {
		return btableDao.findByCroom( crmId );
	}
	
	/**
	 * 根据教室ID 开始时间以及结束时间 获取课节（获取一周的课节
	 * @param crmId 教室Id
	 * @return
	 */
	public List<Btable> findByCroom(String crmId,Date start,Date end) {
		return btableDao.findByCroom( crmId );
	}
	
	public String getDataByRoom(String crmId,Date start,Date end){
		List<Btable> btables=btableDao.findByCroom( crmId );
		
		StringBuilder builder = new StringBuilder( "[" );
		Calendar calendar = Calendar.getInstance();
		
		for (Btable btable : btables) {
			long startTime = 0;
			long endTime = 0;
			
			calendar.setTime( btable.getTime_start() );
			startTime = calendar.getTimeInMillis();
			calendar.setTime( btable.getTime_end() );
			endTime = calendar.getTimeInMillis();
			builder.append( "{'id':'" ).append( btable.getId() )
			   .append( "','start':'" ).append( startTime )
			   .append( "','end':'" ).append( endTime )
			   .append( "','title':'" ).append(btable.getCouid()!=null?btable.getCouid().getTitle():"" )
			   .append( "'}," );
		}
		builder.deleteCharAt(builder.length() - 1);

		builder.append( "]" );
		
		return builder.toString();
	}
	
	/**
	 * 判断同一时间段同一班级不能在不同的教室上课。
	 * @param cls
	 * @param start
	 * @param end
	 * @return
	 */
	public boolean isEixtClass(Cls cls,Date start,Date end){
		return btableDao.isEixtClass(cls, start, end);
	}
	
	/**
	 * 根据条件获取课节
	 * @param crmId 教室Id
	 * @param courId 课程Id
	 * @param deptId 科系Id
	 * @param terId 教师Id
	 * @param gradeId 年级Id
	 * @param calId 班级Id
	 * @return
	 */
	public List<Btable> findByParameter(Croom room,Course courId,
			Dept deptId,Teacher terId,Grade gradeId,Cls calId,String weday,String cal){
		return btableDao.findByParameter(room, courId, deptId, terId, gradeId, calId,weday,cal);
	}
	
	public List<Btable> findByCroomAndWeDay(String weday, String crmId) {
		return btableDao.findByCroomAndWeDay( weday, crmId );
	}

	public List<Croom> findAliveCroom() {
		return (List<Croom>) btableDao.findAliveCroom();
	}
	
	public int deleteByCroom(String crmId) {
		return btableDao.deleteByCroom( crmId );
	}
	
	public String getEventsJson(Teacher teacher) {
		StringBuilder builder = new StringBuilder( "[" );
		Calendar calendar = Calendar.getInstance();
		List<Btable> btables = btableDao.findByTeacher( teacher );

		for (Btable btable : btables) {
			CreContent creContent = creContentService.findCreContentByBtable( btable );
			StringBuilder creCotentBuilder = new StringBuilder();
			
			if (null != creContent) {
				creCotentBuilder
					.append( " title=\"教学目的:" )
					.append( creContent.getAim() )
					.append( "。" )
					.append( creContent.getKeynote() )
					.append( "\"" );
			}
			
			long startTime = 0;
			long endTime = 0;
			
			calendar.setTime( btable.getTime_start() );
			startTime = calendar.getTimeInMillis();
			calendar.setTime( btable.getTime_end() );
			endTime = calendar.getTimeInMillis();
			List<MaterialD> materialDs = creContentService.findMaterialDByBtable( btable );
			StringBuilder mtrdIds = new StringBuilder();
			for (MaterialD materialD : materialDs) {
				mtrdIds.append( materialD.getTitle() ).append( ";" );
			}
		 
			builder.append( "{'id':'" ).append( btable.getId() )
				   .append( "','start':'" ).append( startTime )
				   .append( "','end':'" ).append( endTime )
				   .append( "','title':'" )
				   .append( 
					   new StringBuilder( "<a href=\"#\"" )
					   		.append( creCotentBuilder.toString() )
					   		.append( ">" )
					   		.append(mtrdIds==null?"":"<div style=\"background-color:#0066FF\"><font size=\"2\" color=\"red\">"+ mtrdIds.toString()+"</font></div>") 									
					   		.append( btable.getCouid().getTitle() )
					   		.append( " " )
					   		.append( btable.getCrmid().getCrmTitle() )
					   		.append( "<br/>" )
					   		.append( btable.getDptid().getTitle() )
					   		.append( " " )
					   		.append( btable.getGradeid().getGradeTitle() )
					   		.append( " " )
					   		.append( btable.getClaid().getClsTitle() )
					   		.append( "<br/>" )
					   		.append( "</a>" )
					   		.toString() 
				   ).append( "'}," );
		}
		
		builder.deleteCharAt(builder.length() - 1);

		builder.append( "]" );
		
		return builder.toString();
	}
	
	/**
	 * 根据班级查询课表
	 * @param cls 所属班级
	 * @return
	 */
	public String getEventsJson(Cls cls) {
		return getEventsJson(cls,null,null);
	}
	
	public String getEventsJson(Cls cls,Date start,Date end) {
		StringBuilder builder = new StringBuilder( "[" );
		Calendar calendar = Calendar.getInstance();
		List<Btable> btables = btableDao.findByclaId(cls,start,end);

		for (Btable btable : btables) {
			CreContent creContent = creContentService.findCreContentByBtable( btable );
			StringBuilder creCotentBuilder = new StringBuilder();
			
			if (null != creContent) {
				creCotentBuilder
					.append( " title=\"教学目的:" )
					.append( creContent.getAim() )
					.append( "。" )
					.append( creContent.getKeynote() )
					.append( "\"" );
			}
			
			long startTime = 0;
			long endTime = 0;
			
			calendar.setTime( btable.getTime_start() );
			startTime = calendar.getTimeInMillis();
			calendar.setTime( btable.getTime_end() );
			endTime = calendar.getTimeInMillis();
			List<MaterialD> materialDs = creContentService.findMaterialDByBtable( btable );
			StringBuilder mtrdIds = new StringBuilder();
			for (MaterialD materialD : materialDs) {
				mtrdIds.append( materialD.getTitle() ).append( ";" );
			}
		 
			builder.append( "{'id':'" ).append( btable.getId() )
				   .append( "','start':'" ).append( startTime )
				   .append( "','end':'" ).append( endTime )
				   .append( "','title':'" )
				   .append( 
					   new StringBuilder( "<a href=\"#\"" )
					   		.append( creCotentBuilder.toString() )
					   		.append( ">" )
					   		.append(mtrdIds==null?"":"<div style=\"background-color:#0066FF\"><font size=\"2\" color=\"red\">"+ mtrdIds.toString()+"</font></div>") 									
					   		.append( btable.getCouid().getTitle() )
					   		.append( " " )
					   		.append( btable.getCrmid().getCrmTitle() )
					   		.append( "<br/>" )
					   		.append( "</a>" )
					   		.toString() 
				   ).append( "'}," );
		}
		
		builder.deleteCharAt(builder.length() - 1);

		builder.append( "]" );
		
		return builder.toString();
	}
	
	/**
	 * 
	 * @see 根据班级id和上课时间定位一条基本课表信息
	 * @param clsId   班级id
	 * @param currentTime 
	 * @return
	 */
	public Btable findByClsIdAndLessonTime(final String clsId,final Date lessonTime){
		List<Btable> list=btableDao.findAll(new Specification<Btable>() {
			@Override
			public Predicate toPredicate(Root<Btable> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
				List<Predicate> predicates = Lists.newArrayList();
				Path<Date> start=root.get("time_start");
				Path<Date> end=root.get("time_end");
				Path<Cls> cla=root.get("claid");
				predicates.add(cb.equal(cla.get("clsId"),clsId));
				predicates.add(cb.greaterThanOrEqualTo(end,lessonTime));
				predicates.add(cb.lessThanOrEqualTo(start,lessonTime));
				if (predicates.size() > 0) {
					return cb.and(predicates.toArray(new Predicate[predicates.size()]));
				}
				return cb.conjunction();
			}
		});
		return list.size()>0?list.get(0):null;
	}
	
	
	/**
	 * 
	 * @see 根据老师的用户Id和上课时间定为一条基本课表信息
	 * @param teaUserId   老师对应的用户Id
	 * @param currentTime 
	 * @return
	 */
	public Btable findByTeaUserIdAndLessonTime(final String teaUserId,final Date lessonTime){
		
		List<Btable> list=btableDao.findAll(new Specification<Btable>() {
			@Override
			public Predicate toPredicate(Root<Btable> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
				List<Predicate> predicates = Lists.newArrayList();
				Path<Date> start=root.get("time_start");
				Path<Date> end=root.get("time_end");
				predicates.add(cb.equal(root.get("teaid").get("terUserId"),teaUserId));
				predicates.add(cb.greaterThanOrEqualTo(end,lessonTime));
				predicates.add(cb.lessThanOrEqualTo(start,lessonTime));
				if (predicates.size() > 0) {
					return cb.and(predicates.toArray(new Predicate[predicates.size()]));
				}
				return cb.conjunction();
			}
		});
		return list.size()>0?list.get(0):null;
	}
	
	/**
	 * 根据星期，课节以及教室获取基本课表的一些信息
	 * @param room
	 * @param weday
	 * @param cla
	 * @return
	 */
	public List<Btable> findByCroom(Croom room,String weday,String cla) {
		return btableDao.findByCroom(room, weday, cla);
	}
	
	/**
	 * 更具班级id获取基本课表的一些信息
	 * @param claId 班级Id
	 * @return
	 */
	public List<Btable> findByclaId(Cls claId) {
		return btableDao.findByclaId( claId );
	}
	
	/**
	 * 根据班级和课程获取基本课表的一些信息
	 * @param claId 班级
	 * @param course 课程
	 * @return
	 */
	public List<Btable> findByclaIdAndCourseId(Cls claId,Course course){
		return btableDao.findByclaIdAndCourseId(claId, course);
	}
	
	/**
	 * 更具班级id获取基本课表的一些信息
	 * @param claId 班级Id
	 * @return
	 */
	public Btable findByclaIdAndId(String id,Cls claId) {
		return btableDao.findByclaIdAndId(id, claId );
	}
	
	/**
	 * 根据星期和课节获取不属于当前教室的基本课表的一些信息
	 * @param weday
	 * @param cla
	 * @return
	 */
	public List<Btable> findByWedayAndClass(String weday,String cla,Croom room){
		return btableDao.findByWedayAndClass(weday, cla, room);
	}
	
	/**
	 * 根据教室和开放星期获取当前教室的基本课表的信息
	 * @param room
	 * @param wedayStart
	 * @param wedayEnd
	 * @return
	 */
	public List<Btable> findByCroomAndWedayTF(Croom room,int wedayStart,int wedayEnd){
		return btableDao.findByCroomAndWedayTF(room, wedayStart, wedayEnd);
	}
	
	/**
	 * 根据教室获取所有已经设置过课程的课节
	 * @param room
	 * @return
	 */
	public List<Btable> findIsSettedByCroom(Croom room){
		return btableDao.findIsSettedByCroom(room);
	}
	
	public Btable findByCurrentTime(Date currentTime) {
		return btableDao.findByCurrentTime( currentTime );
	}
}
